package com.myspring.web.view.excel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author : zenghua
 * @version : v0.1 ExcelEntryMethodProcessor.java
 * @since : 2018/4/27 10:47
 */
public class ExcelEntryMethodProcessor implements HandlerMethodReturnValueHandler {
	@Autowired
	private ExcelView excelView;

	/**
	 * 解析方法参数
	 * @param returnType
	 * @return
	 */
	@Override
	public boolean supportsReturnType(MethodParameter returnType) {
		return ExcelEntry.class.isAssignableFrom(returnType.getParameterType());
	}

	@Override
	public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
								  NativeWebRequest webRequest) throws Exception {
		mavContainer.setRequestHandled(true);
		HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

		if (returnValue instanceof ExcelEntry) {
			ExcelEntry excelEntry = (ExcelEntry) returnValue;
			ModelMap model = new ModelMap();
			model.addAttribute(ExeclConstants.EXCEL_HEADER, excelEntry.getTitleList());
			model.addAttribute(ExeclConstants.EXCEL_CONTENT, excelEntry.getContentMap());
			excelView.render(model, request, response);
		} else {
			ModelMap model = new ModelMap();
			model.addAttribute("returnValue", returnValue);
			excelView.render(model, request, response);
		}
	}

}
